#include "cards.h"
#include <QRandomGenerator>

Cards::Cards() {}

Cards::Cards(const Card &card)
{
    add(card);
}

// 添加单张扑克牌
void Cards::add(const Card &card)
{
    m_cards.insert(card);
}

// 添加多张扑克牌
void Cards::add(const Cards &cards)
{
    m_cards.unite(cards.m_cards);
}

// 添加存储多张牌的容器
void Cards::add(const QVector<Cards> &cards)
{
    for (int i = 0; i < cards.count(); ++ i) {
        add(cards.at(i));
    }
}

// 一次性插入多个数据（重载<<）
Cards& Cards::operator <<(const Card &card)
{
    add(card);
    return *this;
}

Cards& Cards::operator <<(const Cards& cards)
{
    add(cards);
    return *this;
}

// 删除单张扑克牌
void Cards::remove(const Card &card)
{
    m_cards.remove(card);
}

 // 删除多张扑克牌
void Cards::remove(const Cards &cards)
{
    m_cards.subtract(cards.m_cards);
}

// 删除存储多张扑克牌
void Cards::remove(const QVector<Cards> &cards)
{
    for (int i = 0; i < cards.size(); ++ i) {
        remove(cards.at(i));
    }
}

// 获取扑克牌的数量
int Cards::cardCount() const
{
    return m_cards.size();
}

// 获取扑克牌的数量
bool Cards::isEmpty() const
{
    return m_cards.isEmpty();
}

// 清空扑克牌
void Cards::clear()
{
    m_cards.clear();
}

// 获取最大点数
Card::CardPoint Cards::maxPoint()
{
    Card::CardPoint max = Card::Card_Begin;
    if (!m_cards.isEmpty()) {
        for (auto it = m_cards.begin(); it != m_cards.end(); ++ it) {
            if (it->getPoint() > max) {
                max = it->getPoint();
            }
        }
    }
    return max;
}

// 获取最小点数
Card::CardPoint Cards::minPoint()
{
    Card::CardPoint min = Card::Card_End;
    if (!m_cards.isEmpty()) {
        for (auto it = m_cards.begin(); it != m_cards.end(); ++ it) {
            if (it->getPoint() < min) {
                min = it->getPoint();
            }
        }
    }
    return min;
}

// 指定点数的牌的数量
int Cards::pointCount(Card::CardPoint point)
{
    int count = 0;
    for (auto it = m_cards.begin(); it != m_cards.end(); ++ it) {
        if (it->getPoint() == point) {
            ++ count;
        }
    }

    return count;
}

// 某张牌是否在某个集合中
bool Cards::contains(const Card& card) const
{
    return m_cards.contains(card);
}

// 某张牌是否在某个集合中
bool Cards::contains(const Cards& cards) const
{
    return m_cards.contains(cards.m_cards);
}

// 随取出一张扑克牌
Card Cards::takeRandomCard()
{
    // 生成随机数
    int randNum = QRandomGenerator::global()->bounded(m_cards.size());
    QSet<Card>::const_iterator it = m_cards.constBegin();
    for (int i = 0; i < randNum; ++ i, ++ it);
    Card card = *it;
    m_cards.erase(it);

    return card;
}

// QSet -> QVector (将无序容器中的扑克牌转换为有效容器中的扑克牌) CardList = QVector<Card>;
CardList Cards::toCardList(SortType type)
{
    CardList list;
    for (auto it = m_cards.begin(); it != m_cards.end(); ++ it) {
        list << *it;
    }

    if (type == Asc) {
        std::sort(list.begin(), list.end(), lessSort);
    } else if (type == Desc) {
        std::sort(list.begin(), list.end(), greaterSort);
    }

    return list;
}
